//通过mutations间接更新state的对象
import {
    RECEIVE_ADDRESS,
    RECEIVE_CATEGORYS,
    RECEIVE_SHOPS,
    RECEIVE_INFO,
    RECEIVE_GOODS,
    RECEIVE_RATINGS,
    INCREMENT_FOOD_COUNT,
    DECREMENT_FOOD_COUNT,
    CLEAR_CART,
    SEARCH_SHOP,
    RELINK_FOODS,
} from './mutations-types'
import {
    reqAddress,
    reqFoodsType,
    reqShops,
    reqShopGoods,
    reqShopInfo,
    reqShopRatings,
    reqSearchShops,
} from '../ajax'
/*
1.定义一个函数
2.发起相应ajax请求
3.将获取到的数据赋值给state中相应的数据对象
*/
export default {
    async getAddress({commit,state}){
    const geohash = state.latitude + ',' + state.longitude
        const result = await reqAddress(geohash)
        if(result.code === 0){
            const address = result.data
            commit(RECEIVE_ADDRESS,{address})
        }
    },
    async getCategorys({commit}){
            const result = await reqFoodsType()
            if(result.code === 0){
                const categorys = result.data
                commit(RECEIVE_CATEGORYS,{categorys})
            }
        },
        async getShops({commit,state}){
            const {longitude,latitude}= state
            const result = await reqShops(longitude,latitude)
            if(result.code === 0){
                const shops = result.data
                commit(RECEIVE_SHOPS,{shops})
            }
        },
        async getGoods({commit},callback){
            const result = await reqShopGoods()
            if(result.code === 0){
                const goods = result.data
                commit(RECEIVE_GOODS,{goods})
                callback && callback()
            }
        },
        async getRatings({commit}){
            const result = await reqShopRatings()
            if(result.code === 0){
                const ratings = result.data
                commit(RECEIVE_RATINGS,{ratings})
            }
        },
        async getInfo({commit}){
            const result = await reqShopInfo()
            if(result.code === 0){
                const info = result.data
                commit(RECEIVE_INFO,{info})
            }
        },
        //同步更新food中的count
        updatefoodCount({commit},{isAdd,food}){
            if(isAdd){
                commit(INCREMENT_FOOD_COUNT,{food})
            }else{
                commit(DECREMENT_FOOD_COUNT,{food})
            }
        },
        //同步移除购物车中所有购物项
        clearCart({commit}){
            commit(CLEAR_CART)
        },
        //异步获取搜索的商品列表
        async getSearchShops({state,commit},keyword){
            const geohash = state.latitude + ',' + state.longitude
            const res = await reqSearchShops(geohash,keyword)
            if(res.code === 0){
                const searchShops = res.data
                commit(SEARCH_SHOP,{searchShops})
            }
        },
        // 刷新后将shopfoods中的food与cartFoods重新关联
        relinkFoods ({commit}) {
            commit(RELINK_FOODS)
        }
}